/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import model.Contact;

/**
 *
 * @author Gautier
 */
public class ContactList extends JList implements ListSelectionListener{
    ArrayList<Contact> al;
    private DefaultListModel l2;
    public int groupActive;
    private ContactDisplay cd;
    
    public ContactList(ArrayList a, ContactDisplay c) {
        super();
        al=a;
        cd=c;
        l2 = new DefaultListModel();
        
        this.setModel(l2);
        this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.addListSelectionListener(this);
    }
    
    public void setUpList(int nb){
        l2.removeAllElements();
        for(int i = 0; i<al.size(); i++){
            if(al.get(i).getGroup()==groupActive)
                l2.addElement(al.get(i).getName() + " " + al.get(i).getFirstName());
        }
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        System.out.println("n"+((ContactList)e.getSource()).getSelectedIndex()); 
        if(((ContactList)e.getSource()).getSelectedIndex() == -1){
            cd.reset();
        } else {
            //Find contact
            String s = (String) l2.get(this.getSelectedIndex());
            for(int i=0; i<al.size(); i++){
                if(s.compareTo(al.get(i).getName() + " " + al.get(i).getFirstName()) == 0){
                    cd.update(al.get(i));
                }
            }
        }
    }
    
}
